<template>
  <div class="step2-form">
    <div class="line"></div>
    <a-form :form="form">
      <label class="real-label">
        <span>{{ $t("breach.steps.step2.business.form.ifreal") }}:</span>
        <a-radio-group
          :value="item.SupplementRealData"
          @change="
            (e) => $emit('changeItem', 'SupplementRealData', e.target.value)
          "
          :disabled="!ifCanEdit"
        >
          <a-radio :value="1">{{
            $t("user.verification-code.requiredLuck11yes")
          }}</a-radio>
          <a-radio :value="2">{{
            $t("user.verification-code.requiredLuck11no")
          }}</a-radio>
        </a-radio-group>
      </label>
      <div class="real-content" v-show="item.SupplementRealData === 1">
        <label class="real-label" v-if="breachMode === 2">
          <span
            >2.
            {{ $t("breach.steps.step4.content.a.supplement.ifagree") }}:</span
          >
          <a-radio-group
            :value="item.SupplementProcessingActivities || 2"
            @change="
              (e) =>
                $emit(
                  'changeItem',
                  'SupplementProcessingActivities',
                  e.target.value
                )
            "
            :disabled="!ifCanEdit"
          >
            <a-radio :value="1">{{
              $t("user.verification-code.requiredLuck11yes")
            }}</a-radio>
            <a-radio :value="2">{{
              $t("user.verification-code.requiredLuck11no")
            }}</a-radio>
          </a-radio-group>
        </label>
        <a-form-item
          v-if="breachMode === 2 && item.SupplementProcessingActivities === 2"
        >
          <a-textarea
            rows="4"
            v-decorator="['SupplementProcessingActivitiesSupplement']"
            :placeholder="$t('breach.steps.step2.ifagree.placeholder')"
          ></a-textarea>
        </a-form-item>
        <a-form-item
          :label="
            (breachMode === 2 ? '3. ' : '2. ') +
            $t('breach.steps.step2.business.form.type')
          "
          class="select-type"
        >
          <a-checkbox-group
            v-decorator="['SupplementInformationType']"
            @change="(value) => (typeList = value)"
            :disabled="!ifCanEdit"
          >
            <div class="details">
              <a-checkbox value="di">{{
                $t("breach.steps.step2.business.form.type.title")
              }}</a-checkbox>
              <a-table
                size="small"
                :data-source="diDataLists"
                bordered
                :pagination="false"
                v-show="typeList.includes('di')"
              >
                <a-table-column key="No" title="No" align="center">
                  <template slot-scope="text, record, ind">
                    {{ ind + 1 }}
                  </template>
                </a-table-column>
                <a-table-column
                  key="DataItemStr"
                  :title="$t('breach.steps.step2.business.form.type.id')"
                  align="center"
                >
                  <template slot-scope="text, record">
                    <a-select
                      :placeholder="$t('app.setting.themecolor.dust.select')"
                      v-model="record.PersonalInformationDataItem"
                      show-search
                      :show-arrow="false"
                      :filter-option="false"
                      :disabled="!ifCanEdit"
                      :dropdownMatchSelectWidth="false"
                      @focus="filterSearchInputOption"
                      @search="filterSearchInputOption"
                      @change="handleDiChange"
                    >
                      <a-select-option
                        v-for="item in dataItemsSearchData"
                        :value="item.value"
                        :key="item.label + item.value"
                      >
                        <a-tooltip placement="topLeft">
                          <template slot="title">
                            {{ item.label }}
                          </template>
                          {{ item.label }}
                        </a-tooltip>
                      </a-select-option>
                    </a-select>
                  </template>
                </a-table-column>
                <a-table-column
                  key="PersonalInformationSensitiveStr"
                  data-index="PersonalInformationSensitiveStr"
                  :title="
                    $t('breach.steps.step2.business.form.type.sensitivity')
                  "
                  align="center"
                >
                  <template slot-scope="text, record">
                    {{
                      record.PersonalInformationSensitiveStr
                        ? record.PersonalInformationSensitiveStr
                        : "-"
                    }}
                  </template>
                </a-table-column>
                <a-table-column
                  key="PersonalInformationLevelStr"
                  data-index="PersonalInformationLevelStr"
                  :title="$t('breach.steps.step2.business.form.type.level')"
                  align="center"
                >
                  <template slot-scope="text, record">
                    {{
                      record.PersonalInformationLevelStr
                        ? record.PersonalInformationLevelStr
                        : "-"
                    }}
                  </template>
                </a-table-column>
                <a-table-column
                  key="PersonalInformationProtectLevelStr"
                  data-index="PersonalInformationProtectLevelStr"
                  :title="$t('breach.steps.step2.business.form.type.savelevel')"
                  align="center"
                >
                  <template slot-scope="text, record">
                    {{
                      record.PersonalInformationProtectLevelStr
                        ? record.PersonalInformationProtectLevelStr
                        : "-"
                    }}
                  </template>
                </a-table-column>
                <a-table-column
                  key="operate"
                  :title="$t('di.menus')"
                  align="center"
                >
                  <template slot-scope="text, record">
                    <a-button
                      type="link"
                      :disabled="!ifCanEdit"
                      @click="delRow(record.Id)"
                      >{{ $t("app.setting.copy") }}</a-button
                    >
                  </template>
                </a-table-column>
              </a-table>
              <a-button
                icon="appstore"
                type="link"
                @click="diDataLists.push({ Id: +new Date() })"
                v-show="typeList.includes('di')"
                :disabled="!ifCanEdit"
                >{{ $t("breach.steps.step2.business.form.type.add") }}</a-button
              >
            </div>
            <div class="other">
              <a-checkbox value="other">{{
                $t("breach.steps.step2.business.form.type.other")
              }}</a-checkbox>
              <a-textarea
                rows="4"
                :placeholder="
                  $t('breach.steps.step2.business.form.type.other.placeholder')
                "
                v-show="typeList.includes('other')"
                v-decorator="['SupplementOtherInformation']"
                :disabled="!ifCanEdit"
              ></a-textarea>
            </div>
          </a-checkbox-group>
        </a-form-item>
        <a-row :gutter="24">
          <a-col :span="12">
            <label class="real-label">
              <span
                >{{
                  (breachMode === 2 ? "4. " : "3. ") +
                  $t("breach.steps.step2.business.form.owner")
                }}:</span
              >
              <a-select
                mode="multiple"
                @change="changeselect"
                :value="item.SupplementController"
                :placeholder="$t('user.login.forgot-password')"
                :disabled="!ifCanEdit"
                show-search
                option-filter-prop="children"
              >
                <a-select-option
                  v-for="item in systemControllerSourceData"
                  :value="item.value"
                  :key="item.label + item.value"
                  >{{ item.label }}
                </a-select-option>
              </a-select>
            </label>
          </a-col>
          <a-col :span="12" v-if="otherflag">
            <a-form-item
              label="Other"
              :label-col="{ span: 4 }"
              :wrapper-col="{ span: 20 }"
              labelAlign="left"
            >
              <!-- 内容信息 -->
              <a-input
                v-decorator="[
                  'SupplementControllerOther',
                  {
                    rules: [
                      {
                        required: true,
                        message: $t(
                          'breach.steps.step2.business.form.owner.other'
                        ),
                      },
                    ],
                  },
                ]"
                :placeholder="
                  $t('breach.steps.step2.business.form.owner.other')
                "
                :disabled="!ifCanEdit"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <step-2-form-half
          ref="step2FormHalf"
          :item="item"
          :ifCanEdit="ifCanEdit"
          :breachMode="breachMode"
          :breachDetail="breachDetail"
          :form="form"
          @changeItem="(...rest) => $emit('changeItem', ...rest)"
        />
      </div>
      <div class="not-real" v-show="item.SupplementRealData === 2">
        <a-form-item :label="$t('breach.steps.step2.business.form.describe')">
          <a-textarea
            :placeholder="
              $t('breach.steps.step2.business.form.describe.placeholder')
            "
            rows="4"
            v-decorator="[
              'SupplementDescribe',
              {
                rules: [
                  {
                    required: true,
                    message: $t(
                      'breach.steps.step2.business.form.describe.placeholder'
                    ),
                  },
                ],
              },
            ]"
            :disabled="!ifCanEdit"
          >
          </a-textarea>
        </a-form-item>
      </div>
      <upload-file
        ref="uploadFile"
        :InfoSupplementId="item.Id"
        :breachId="breachDetail?.Id"
        :tip="$t('breach.steps.step1.content.form.file.tip')"
        :disabled="!ifCanEdit"
      />
      <a-form-item
        :label="$t('breach.steps.step2.business.form.call.remark')"
        v-if="breachMode === 1"
        v-show="item.SupplementRealData === 1 || breachMode === 2"
      >
        <a-textarea
          :placeholder="
            $t('breach.steps.step2.business.form.remark.placeholder')
          "
          rows="4"
          v-decorator="[
            'SupplementRemark',
            {
              rules: [
                {
                  required: true,
                  message: $t(
                    'breach.steps.step2.business.form.remark.placeholder'
                  ),
                },
              ],
            },
          ]"
          :disabled="!ifCanEdit"
        >
        </a-textarea>
      </a-form-item>
    </a-form>
    <div class="form-buttons">
      <!-- 退回 -->
      <a-button
        type="primary"
        v-if="role.includes('processor') && item.SupplementStatus === 3"
        @click="back"
      >
        {{ $t("breach.steps.step2.business.form.buttons.back") }}
      </a-button>
      <template
        v-else-if="role.includes('business') || role.includes('Collaborator')"
      >
        <!-- 保存 -->
        <a-button
          type="primary"
          class="mr-[20px]"
          :disabled="!ifCanEdit"
          @click="$emit('saveItem', item, 'draft')"
        >
          {{ $t("breach.steps.step2.business.form.buttons.save") }}
        </a-button>
        <!-- 提交 -->
        <a-button :disabled="!ifCanEdit" @click="submitItem(item)">
          {{ $t("breach.steps.step2.business.form.buttons.submit") }}
        </a-button>
      </template>
    </div>
    <a-modal
      :visible="visible"
      :title="$t(modalMap[modalMode].title)"
      :closable="false"
      dialogClass="step2-form-modal"
    >
      {{ $t(modalMap[modalMode].content) }}:
      <a-textarea
        rows="4"
        :placeholder="$t(modalMap[modalMode]?.contentPlaceholder)"
        :disabled="modalMode === 'tip'"
        v-model="modalMap.backReason"
        class="mt-[10px] mb-[10px]"
      ></a-textarea>
      <a-checkbox v-model="modalMap.checked" v-if="modalMode === 'tip'">{{
        $t(modalMap[modalMode]?.confirm)
      }}</a-checkbox>
      <template slot="footer">
        <div class="buttons">
          <template v-if="modalMode === 'tip'">
            <a-button type="primary" @click="gotIt">OK</a-button>
          </template>
          <template v-else>
            <a-button @click="closeModal">{{
              $t("app.setting.content-width.fluid2222333")
            }}</a-button>
            <a-button type="primary" :loading="btnLoading" @click="runBack">{{
              $t("app.setting.content-width.fluid2222")
            }}</a-button>
          </template>
        </div>
      </template>
    </a-modal>
  </div>
</template>

<script>
import { childataItems, dccDataItemsSelect } from "@/api/dcc";
import { configurationSelect } from "@/api/configs";
import step2FormHalf from "./step2FormHalf.vue";
import uploadFile from "@/components/uploadFile/index.vue";
import { confirmRefuse, getRefuse } from "@/api/dataBreach/form";
export default {
  name: "step2Form",
  props: [
    "item",
    "lang",
    "ifCanEdit",
    "role",
    "breachMode",
    "current",
    "breachDetail",
  ],
  components: { step2FormHalf, uploadFile },
  data() {
    return {
      form: this.$form.createForm(this),
      diDataLists: [],
      dataItemsSearchData: [],
      otherflag: false,
      systemControllerSourceData: [],
      typeList: [],
      visible: false,
      modalMode: "back",
      modalMap: {
        backReason: "",
        checked: false,
        back: {
          title: "breach.steps.step2.modal.back.title",
          content: "breach.steps.step2.modal.back.content",
          contentPlaceholder:
            "breach.steps.step2.modal.back.content.placeholder",
        },
        tip: {
          title: "breach.steps.step2.modal.tip.title",
          content: "breach.steps.step2.modal.tip.content",
          confirm: "breach.steps.step2.modal.tip.know",
        },
      },
      tipInfoId: -1,
      btnLoading: false
    };
  },
  watch: {
    item: {
      handler(newVal) {
        this.diDataLists = newVal.PersonalInformation || [];
        setTimeout(() => {
          // 进行值回显处理
          let resVal = { ...newVal };
          this.typeList = resVal.SupplementInformationType;
          this.form.setFieldsValue(resVal);
        });
      },
      immediate: true,
    },
    current: {
      handler(newVal) {
        if (newVal === 1) {
          this.init();
        }
      },
      immediate: true,
    },
    lang: {
      handler() {
        this.filterSearchInputOption();
      },
      immediate: true,
    },
  },
  methods: {
    async init() {
      if (
        this.item.SupplementStatus === 2 &&
        this.item.SupplementUser === this.$store.state.user.info.YtAdminName
      ) {
        // 弹框提示被退回
        let { data } = await getRefuse({
          SupplementId: this.item.Id,
        });
        if (
          data &&
          data.BreachCommentsPrompt &&
          data.BreachCommentsPrompt === 1
        ) {
          this.tipInfoId = data.Id;
          this.modalMode = "tip";
          this.modalMap.backReason = data.BreachCommentsInfo;
          this.visible = true;
        }
      }
      this.filterSearchInputOption();
      const { data: systemControllerSourceData } = await configurationSelect({
        state: 11,
      });
      this.systemControllerSourceData = systemControllerSourceData;
      this.changeselect(this.item.SupplementController);
    },
    async filterSearchInputOption(inputs) {
      const { data: dataItemsSearchData } = await dccDataItemsSelect({
        search: inputs,
      });
      if (this.lang) {
        this.dataItemsSearchData = dataItemsSearchData;
      } else {
        this.dataItemsSearchData = [];
        for (var i = 0; i < dataItemsSearchData.length; i++) {
          this.dataItemsSearchData.push({
            label: dataItemsSearchData[i].labelEn,
            value: dataItemsSearchData[i].value,
          });
        }
      }
    },
    async handleDiChange(e) {
      try {
        var tempLists = [];
        const { data } = await childataItems({ id: e });
        for (var i = 0; i < this.diDataLists.length; i++) {
          let item = this.diDataLists[i];
          if (item.PersonalInformationDataItem == e) {
            item.PersonalInformationLevel = data[0].SourceDataLevel;
            item.PersonalInformationLevelStr = data[0].DateLevel;
            item.PersonalInformationSensitive = data[0].SourceSensitivityLevel;
            item.PersonalInformationSensitiveStr = data[0].SensitivityLevel;
            item.PersonalInformationProtectLevel =
              data[0].SourceProtectionLevel;
            item.PersonalInformationProtectLevelStr = data[0].ProtectionLevel;
          }
          tempLists.push(item);
        }
        this.diDataLists = tempLists;
      } catch (error) {
        this.$message.error(error);
      }
    },
    delRow(Id) {
      this.diDataLists = this.diDataLists.filter((item) => item.Id !== Id);
    },
    //数据控制者是否出现other获取
    changeselect(value) {
      if (value) {
        if (typeof value === "string") {
          value = value.split(",").map((item) => Number(item));
        }
        this.$emit("changeItem", "SupplementController", value);
        let item2 = [];
        value.forEach((item) => {
          this.systemControllerSourceData.forEach((item1) => {
            if (item == item1.value) {
              item2.push(item1.label);
            }
          });
        });
        if (item2.includes("Other")) {
          this.otherflag = true;
          this.$nextTick(() => {
            this.form.setFieldsValue({
              SupplementControllerOther: this.item.SupplementControllerOther,
            });
          });
        } else {
          this.otherflag = false;
        }
      }
    },
    back() {
      this.visible = true;
      this.modalMode = "back";
    },
    gotIt() {
      if (this.modalMap.checked && this.tipInfoId !== -1) {
        confirmRefuse({
          Id: this.tipInfoId,
          BreachCommentsPrompt: 2,
        });
      }
      this.closeModal();
    },
    closeModal() {
      this.modalMap.backReason = "";
      this.modalMap.checked = false;
      this.visible = false;
    },
    // 退回
    runBack() {
      this.btnLoading = true
      this.$emit("saveDraft", "refresh", {
        Id: this.item.Id,
        BreachCommentsInfo: this.modalMap.backReason,
      });
      this.closeModal();
      this.btnLoading = false
    },
    getAllLists() {
      let diCopy = this.diDataLists ? [...this.diDataLists] : [];
      diCopy.forEach((item) => {
        item.InformationId = item.Id > 1000000 ? undefined : item.Id;
        item.Id = undefined;
      });
      let BreachFileArr = this.$refs.uploadFile.listData.filter(
        (item) => item.ifNew
      );
      BreachFileArr.forEach((element) => {
        element.Id = undefined;
        element.BreachId = this.breachDetail?.Id;
        element.InfoType = 2;
        element.InfoSupplementId = this.item.Id;
      });
      return {
        BreachSupplementDetailArr: this.$refs.step2FormHalf.getAllLists(),
        BreachSupplementPersonalInformationArr: diCopy,
        BreachFileArr,
      };
    },
    submitItem(row) {
      // 是真实数据
      let validateList = [];
      if (row.SupplementRealData === 1) {
        validateList.push("SupplementRemark");
        if (this.otherflag) {
          validateList.push("SupplementControllerOther");
        }
      } else {
        validateList.push("SupplementDescribe");
      }
      this.form.validateFields(validateList, (err) => {
        if (!err) {
          this.$emit("saveItem", row, "submit");
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
.step2-form {
  transition: all 1s;
  overflow: hidden;
  margin: 10px 0;
  padding: 0 20px;
  .line {
    width: 100%;
    height: 2px;
    background-color: #bbb;
    margin-bottom: 10px;
  }
  :deep(label.real-label) {
    margin-bottom: 12px;
    color: rgba(0, 0, 0, 0.85);
    display: flex;
    align-items: center;
    & > span {
      line-height: 40px;
      margin-right: 20px;
      flex-shrink: 0;
      & + * {
        flex: 1;
      }
    }
  }
  :deep(.real-content) {
    .select-type,
    .select-from {
      .ant-checkbox-wrapper {
        margin-top: 12px;
      }
      .ant-form-item-children {
        display: block;
        width: 100%;
        .ant-checkbox-group {
          width: 100%;
          .ant-checkbox-wrapper {
            margin-bottom: 12px;
          }
        }
      }
    }
  }
  .form-buttons {
    display: flex;
    justify-content: center;
  }
}
</style>
<style lang="less">
.step2-form-modal {
  textarea {
    resize: none;
  }
  .buttons {
    display: flex;
    justify-content: center;
  }
}
</style>